import React, { Component } from 'react';
import axios from 'axios';
import PubSub from 'pubsub-js';

export default class Search extends Component {
    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input ref={el => this.iptEle = el} type="text" placeholder="enter the name you search" />&nbsp;
                    <button onClick={this.search}>Search</button>
                </div>
            </section>
        )
    }

    search = () => {
        // PubSub.publish('updateList','我这个seacch消息发布');
        const { value } = this.iptEle;//拿到用户输入的内容
        console.log(value);

        //只要我开始点击搜索，就说明不再是没有请求过了，所以需要改变state的isFirst为false
        PubSub.publish('updateList', { items: [], isFirst: false, isLoading: true, errMsg: '' });
        /* 
            items: [],
            isFirst: true,//保存用户是否第一次请求
            isLoading,//保存是否在加载中
            errMsg: '请求错误',         
        */

        //发送axios请求
        axios.get('https://api.github.com/search/users?', {
            params: {
                q: value
            }
        })
            .then(res => {
                //console.log(res);
                console.log(res.data.items);
                const userItems = res.data.items;
                //调用父组件的方法
                PubSub.publish('updateList', { items: userItems, isFirst: false, isLoading: false, errMsg: '' });

            })
            .catch(reason => {
                console.log(reason);
                PubSub.publish('updateList', { items: [], isFirst: false, isLoading: false, errMsg: reason });

            })
    }
}


/*  res.data.items
avatar_url: "https://avatars.githubusercontent.com/u/1825798?v=4"
events_url: "https://api.github.com/users/1/events{/privacy}"
followers_url: "https://api.github.com/users/1/followers"
following_url: "https://api.github.com/users/1/following{/other_user}"
gists_url: "https://api.github.com/users/1/gists{/gist_id}"
gravatar_id: ""
html_url: "https://github.com/1"
id: 1825798
login: "1"
node_id: "MDQ6VXNlcjE4MjU3OTg="
organizations_url: "https://api.github.com/users/1/orgs"
received_events_url: "https://api.github.com/users/1/received_events"
repos_url: "https://api.github.com/users/1/repos"
score: 1
site_admin: false
starred_url: "https://api.github.com/users/1/starred{/owner}{/repo}"
subscriptions_url: "https://api.github.com/users/1/subscriptions"
type: "User"
url: "https://api.github.com/users/1"


*/
